import socket, os

server = socket.socket()
server.bind(('localhost', 9999))

server.listen()

while True:
    conn, addr = server.accept()
    while True:
        data = conn.recv(1024)
        if not data:
            print('客户端已断开')
            break
        print('执行指令：', data)
        cmd_res = os.popen(data.decode()).read()
        if len(cmd_res) == 0:
            cmd_res = 'cmd has not output'
        conn.send(str(len(cmd_res.encode())).encode('utf-8'))   #先发大小给客户端

        client_ack = conn.recv(1024)    #防止沾包
        print(client_ack.decode())

        conn.send(cmd_res.encode('utf-8'))

server.close